package com.atung.merchant.service.impl;

import com.atung.merchant.config.auth.AuthUserMangerContext;
import com.atung.merchant.enums.MenuState;
import com.atung.merchant.enums.OrderState;
import com.atung.merchant.enums.RoomState;
import com.atung.merchant.mapper.*;
import com.atung.merchant.po.*;
import com.atung.merchant.service.HomeService;
import com.atung.merchant.vo.MealMenuTypeResponse;
import com.atung.merchant.vo.ResponseMerchantUser;
import com.atung.merchant.vo.RoomInfoResponse;
import com.atung.merchant.vo.SettlementListResponse;
import com.atung.merchant.vo.query.QueryRoomInfoRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @author Administrator
 */
@Service
public class HomeServiceImpl implements HomeService {
    @Resource
    private BusMerchantRoomMapper busMerchantRoomMapper;
    @Resource
    private BusMerchantOrderMapper busMerchantOrderMapper;

    @Resource
    private BusOrderMenuMapper busOrderMenuMapper;
    @Resource
    private BusMerchantMenuTypeMapper busMerchantMenuTypeMapper;
    @Resource
    private BusMerchantUserMapper busMerchantUserMapper;


    @Override
    public RoomInfoResponse getRoomListService(QueryRoomInfoRequest queryRoomInfoRequest) {

        QueryWrapper<BusMerchantRoom> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("merchant_id", AuthUserMangerContext.getMerchantId());
        List<BusMerchantRoom> busMerchantRooms = busMerchantRoomMapper.selectList(queryWrapper);
        AtomicInteger useRoom = new AtomicInteger(0);
        AtomicInteger noUseRoom = new AtomicInteger(0);
        busMerchantRooms.stream().forEach(item -> {
            //使用中
            if (item.getRoomState().equals(RoomState.useRoom.ordinal())) {
                useRoom.incrementAndGet();
                //查询当前订单
            } else {
                //未使用
                noUseRoom.incrementAndGet();
            }
        });
        return RoomInfoResponse.builder().useRoomCount(useRoom.get()
        ).noUseRoomCount(noUseRoom.get()).build();
    }

    @Override
    public List<SettlementListResponse> getSettlementListService() {
        //获取待结算订单
        QueryWrapper<BusMerchantOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("merchant_id", AuthUserMangerContext.getMerchantId());
        queryWrapper.eq("state", OrderState.AWAIT.ordinal());
        queryWrapper.orderByDesc("creator_time");
        List<BusMerchantOrder> busMerchantOrders = busMerchantOrderMapper.selectList(queryWrapper);
        return busMerchantOrders.stream().map(item -> {
            QueryWrapper<BusOrderMenu> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("order_id", item.getId());
            List<BusOrderMenu> busOrderMenus = busOrderMenuMapper.selectList(queryWrapper1);
            BigDecimal amount = busOrderMenus.stream()
                    .map(BusOrderMenu::getMenuPrice).reduce(BigDecimal.ZERO.stripTrailingZeros(), BigDecimal::add);
            long foodNumber = busOrderMenus.stream().count();
            return SettlementListResponse.builder()
                    .id(item.getId())
                    .roomName(item.getRoomName())
                    .foodNumber(foodNumber)
                    .creatorTime(item.getCreatorTime())
                    .orderAmount(amount).build();

        }).collect(Collectors.toList());
    }

    @Override
    public List<MealMenuTypeResponse> getSettlementMenuTypeService() {
        QueryWrapper<BusOrderMenu> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("merchant_id", AuthUserMangerContext.getMerchantId());
        queryWrapper.eq("menu_state", MenuState.AWAIT.ordinal());
        List<BusOrderMenu> busMerchantOrders = busOrderMenuMapper.selectList(queryWrapper);
        Map<Long, Long> menuTypeIdCounts = busMerchantOrders.stream()
                .collect(Collectors.groupingBy(BusOrderMenu::getMenuTypeId, Collectors.counting()));

        List<MealMenuTypeResponse> collect = menuTypeIdCounts.keySet().stream().map(item -> {
            BusMerchantMenuType busMerchantMenuType = busMerchantMenuTypeMapper.selectById(item);
            if (Objects.nonNull(busMerchantMenuType)) {
                return MealMenuTypeResponse.builder()
                        .id(busMerchantMenuType.getId())
                        .name(busMerchantMenuType.getName())
                        .value(menuTypeIdCounts.get(item).intValue()).build();
            }
            return null;

        }).collect(Collectors.toList());

        Integer sum = menuTypeIdCounts.values().stream().reduce(0L, Long::sum).intValue();
        MealMenuTypeResponse allTYpe = MealMenuTypeResponse.builder()
                .id(null)
                .name("全部")
                .value(sum)
                .check(true)
                .build();
        collect.add(0, allTYpe);
        return collect;
    }

    @Override
    public ResponseMerchantUser getUserInfoService() {

        QueryWrapper<BusMerchantUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("merchant_id", AuthUserMangerContext.getMerchantId());
        queryWrapper.eq("id", AuthUserMangerContext.getUserId());
        BusMerchantUser busMerchantUsers = busMerchantUserMapper.selectOne(queryWrapper);
        if (Objects.isNull(busMerchantUsers)) {
            return null;
        }
        String role = busMerchantUsers.getType().equals(Integer.valueOf(0)) ? "管理员" : "员工";
        return ResponseMerchantUser.builder()
                .name(busMerchantUsers.getName())
                .password("******")
                .phone(busMerchantUsers.getPhone())
                .role(role)
                .id(busMerchantUsers.getId())
                .build();
    }

    private static Long betweenHours(String dateTime1) {
        try {
            LocalDateTime localDateTime = LocalDateTime.now();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = sdf.parse(dateTime1);
            LocalDateTime localDateTime1 = date.toInstant()
                    .atZone(ZoneId.systemDefault())
                    .toLocalDateTime();
            return ChronoUnit.MILLIS.between(localDateTime, localDateTime1);
        } catch (Exception e) {

        }
        return 0L;
    }
}
